package com.zhangxujie.litewords.ui;

import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.preference.EditTextPreference;
import android.text.InputType;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.SwitchPreferenceCompat;

import com.zhangxujie.litewords.R;
import com.zhangxujie.litewords.api.Const;
import com.zhangxujie.litewords.api.GlideCacheUtil;

public class SettingsActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings_activity);


        if (savedInstanceState == null) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.settings, new SettingsFragment())
                    .commit();
        }
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }


    }


    public static class SettingsFragment extends PreferenceFragmentCompat {

        private SwitchPreferenceCompat reciteSettingBar;
        private SharedPreferences mSpf;
        private Preference clearcache;
        private Preference settingsAbout;
        private EditTextPreference settingWordsNum;

        public SettingsFragment() {
        }

        @Override
        public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
            setPreferencesFromResource(R.xml.root_preferences, rootKey);

            //查找和初始化菜单组件
            initComponent();


            setListeners();


        }

        private void setListeners() {
            final Context ctx = getContext();

            //setting-bar
            reciteSettingBar.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(Preference preference, Object newValue) {

                    SharedPreferences.Editor editor = mSpf.edit();
                    editor.putBoolean(Const.SETTING_RECITE_SETTINGBAR, (Boolean) newValue);
                    editor.apply();
//                    Log.d("sig:setting", "onCheckedChanged: "+isChecked);
                    reciteSettingBar.setChecked(!((SwitchPreferenceCompat) preference).isChecked());
//                    Toast.makeText(getContext(), newValue.toString(), Toast.LENGTH_SHORT).show();
                    return false;
                }
            });

            //清除缓存
            clearcache.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference preference) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
                    builder.setTitle("清除缓存");
                    builder.setMessage(String.format("是否清除图片缓存（%s）。注意：清除缓存后，图片需要重新从网络加载!", GlideCacheUtil.getInstance().getCacheSize(ctx)));
                    builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            GlideCacheUtil.getInstance().clearImageAllCache(ctx);
                            Toast.makeText(ctx, "总共释放空间：" + GlideCacheUtil.getInstance().getCacheSize(ctx), Toast.LENGTH_SHORT).show();
                        }
                    });
                    builder.setNegativeButton("否", null);
                    builder.show();

                    return false;
                }
            });


            settingsAbout.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference preference) {

                    AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
                    builder.setTitle("关于");
                    builder.setMessage(String.format("作者：张旭杰\n使用注意：\n\t1、下拉刷新10个单词。\n\t2、使用时间久了需要注意清除图片缓存。\n\t3、查询单词会先从本地数据库查询，如果没有会联网查询。\n\t4、记忆模式：可切换记忆单词模式和背单词模式", GlideCacheUtil.getInstance().getCacheSize(ctx)));
                    builder.setPositiveButton("是", null);
                    builder.show();


                    return false;
                }
            });

            settingWordsNum.setOnBindEditTextListener(new EditTextPreference.OnBindEditTextListener() {
                @Override
                public void onBindEditText(@NonNull EditText editText) {
                    editText.setInputType(InputType.TYPE_CLASS_NUMBER);
                    Log.d("settingWordsNum", "onBindEditText: " + editText.getText().toString());
                    setIntSharedPreferences(Const.NUM_OF_WORDS, Integer.parseInt(editText.getText().toString()));
                }


            });


        }

        private void setIntSharedPreferences(String name, int val) {
            SharedPreferences.Editor editor = mSpf.edit();
            editor.putInt(name, val);
            editor.commit();
        }

        private void initComponent() {
            mSpf = getActivity().getSharedPreferences("setting", MODE_PRIVATE);
            reciteSettingBar = findPreference("recite_setting_bar");
            clearcache = findPreference("clear_cache");
            reciteSettingBar.setChecked(mSpf.getBoolean(Const.SETTING_RECITE_SETTINGBAR, true));
            settingsAbout = findPreference("settings_about");
            settingWordsNum = findPreference("setting_wordsnum");
        }


    }
}